import KoaRouter from 'koa-router'
import Config from '@/config/Config'
import verifyToken from '@/middlewares/verifyToken'
import { Models } from '@/common/typings/modle'
import { Success } from '@/core/HttpException'
import { command } from '@/server/mysql'
const router = new KoaRouter({
  prefix: `${Config.API_PREFIX}v1/system/role`,
})
router.post('/isAdmin', verifyToken, async (ctx: Models.Ctx) => {
  const { userId } = ctx.request.body as any
  throw new Success({
    data: isAdmin(ctx, userId),
  })
})
export default router

export async function isAdmin(ctx: Models.Ctx, userId?: any) {
  if ('isAdmin' in ctx.auth) {
    return ctx.auth.isAdmin
  }
  const count = (
    await command(
      `SELECT COUNT(*) AS count FROM system_user_role ur WHERE ur.user_id = '${
        userId || ctx.auth.id
      }' AND ur.role_id = (SELECT r.id FROM system_role r WHERE r.role_code = 'admin');`,
    )
  ).results[0].count
  const ia = count === 1
  ctx.auth = {
    ...ctx.auth,
    isAdmin: ia,
  }
  return ia
}
